<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总记录数: {{ total }} 条</span>
        </template>
        <template #right>
          <el-button type="warning" size="small" @click="$router.push('/employees/import')">excel导入</el-button>
          <el-button type="danger" size="small" @click="hExcel">excel导出</el-button>
          <el-button type="primary" size="small" @click="showDialog=true">新增员工</el-button>
        </template>
      </page-tools>

      <el-card style="margin-top: 10px;">
        <el-table border :data="list">
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="头像" prop="staffPhoto">
            <template v-slot="{row}">
              <ImageHolder :src="row.staffPhoto" />
            </template>
          </el-table-column>
          <el-table-column label="工号" prop="workNumber" />
          <el-table-column label="聘用形式">

            <template v-slot="{row}">
              {{ formatEmployment(row.formOfEmployment) }}
            </template>

          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column sortable label="入职时间" prop="timeOfEntry">

            <template v-slot="{row}">
              {{ formatDate(row.timeOfEntry) }}
            </template>

          </el-table-column>
          <el-table-column label="操作" width="280">
            <template v-slot="{row}">
              <el-button type="text" size="small" @click="$router.push('/employees/detail/'+row.id)">查看</el-button>
              <el-button type="text" size="small">分配角色</el-button>
              <el-button type="text" size="small" @click="hDel(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <div style="height: 60px; margin-top: 10px">
            <!-- 分页 -->
            <el-pagination
              :current-page="q.page"
              :page-sizes="[5, 10, 20, 30]"
              :page-size="q.size"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              @size-change="hSizeChange"
              @current-change="hCurrentChange"
            />
          </div>
        </el-row>
      </el-card>
      <el-dialog
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        top="50px"
        style="margin-buttom=100px"
        title="新增员工"
        :visible.sync="showDialog"
        @closed="hClosed"
      >
        <addor-edit v-if="showDialog" @success="success" @hclone="hclone" />
      </el-dialog>
    </div>
  </div>
</template>
<script>
import { delEmployee, getEmployeeList } from '@/api/employees'
import addorEdit from './empDialog'
import employeeEnum from '@/constant/employees'
import dayjs from 'dayjs'
// 将工具封装到工具文件夹内，excel导出调用，格式化日期
import { formatDate } from '@/utils/index'
const hireTypeMap = {}
employeeEnum.hireType.forEach(item => {
  hireTypeMap[item.id] = item.value
})
export default {
  components: {
    addorEdit
  },
  data() {
    return {
      showDialog: false,

      list: [],
      total: 0,
      q: {
        page: 1, // 当前页码
        size: 5 // 每页几条

      }
    }
  },
  created() {
    this.loadEmployeeList()
  },
  methods: {
    async loadEmployeeList() {
      const res = await getEmployeeList(this.q)
      this.list = res.data.rows
      this.total = res.data.total
    },
    hclone() {
      this.showDialog = false
    },
    formatEmployment(code) {
      return hireTypeMap[code]
    },
    formatDate(date) {
      return dayjs(date).format('YYYY-MM-DD')
    },
    hCurrentChange(page) {
      // 1. 更新页码
      this.q.page = page
      // 2. 重发请求
      this.loadEmployeeList()
    },
    hSizeChange(size) {
      // 1. 更新每页的条数
      this.q.size = size
      // 2. 重发请求
      this.loadEmployeeList()
    },
    async hDel(id) {
      try {
        await this.$confirm('真的要删除吗', '提示', { type: 'warning' })
        const res = await delEmployee(id)
        this.$message.success(res.message)
        if (this.list.length === 1 && this.q.page > 1) {
          this.q.page--
        }
        this.loadEmployeeList()
      } catch (error) {
        if (error === 'cancel') return
        this.$message.error(error.message)
      }
    },
    hClosed() {
      // this.$refs.empDialog.resetForm()
    },
    success() {
      this.showDialog = false
      if (this.total % this.q.size === 0) {
        this.total++
      }
      this.q.page = Math.ceil(this.total / this.q.size)
      this.loadEmployeeList()
    },
    async  hExcel() {
      const mapInfo = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      const res = await getEmployeeList({ page: 1, size: this.total })
      const list = res.data.rows
      const first = list[0]
      if (!first) return
      const header = Object.keys(first).map(enkey => mapInfo[enkey])
      // const header = Object.values(mapInfo)
      const data = list.map(item => {
        const code = item['formOfEmployment']
        item['formOfEmployment'] = hireTypeMap[code]

        if (item['timeOfEntry'] || item['correctionTime']) {
          item['timeOfEntry'] = formatDate(new Date(item['timeOfEntry']))
          item['correctionTime'] = formatDate(new Date(item['correctionTime']))
        }
        return Object.values(item)
      })
      // console.log(header)
      const excel = await import('@/vendor/Export2Excel')
      // excel表示导入的模块对象
      excel.export_json_to_excel({
        header, // 表头 必填
        data, // 具体数据 必填
        filename: '员工数据', // 文件名称
        autoWidth: true, // 宽度是否自适应
        bookType: 'xlsx' // 生成的文件类型
      })
    }

  }
}
</script>
